<?php

namespace App\Services\Game\Setting\Config;

use App\Services\Service;
use App\Mappers\DataMapper;
use App\Models\Game\Config\Game\System as ConfigSystem;
use App\Models\Game\Config\Game\Platform as ConfigPlatform;
use Illuminate\Support\Arr;

class CommonService extends Service
{

    /**
     * 获取配置
     *
     * @param string $gameCode
     * @return array
     */
    public function getConfig($gameCode)
    {
        return ConfigSystem::findByGame($gameCode)->config ?? [];
    }

    /**
     * 更新配置
     *
     * @param string $gameCode
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function update($gameCode, $request)
    {
        // 配置数据映射
        $data = DataMapper::make($request)->toArray();

        // 创建或修改配置
        $config = ConfigSystem::updateOrCreateByGame($gameCode, $data);

        // 通知游戏端配置修改
        $config->syncGameService();

        return $config->config;
    }

    /**
     * 获取配置【平台】
     *
     * @param string $gameCode
     * @param string $platCode
     * @return array
     */
    public function getConfigPlat($gameCode, $platCode)
    {
        // 系统配置
        // $configSystem = ConfigSystem::findByGame($gameCode)->config ?? [];
        // 平台配置
        $configPlatform = ConfigPlatform::findByPlatGame($platCode, $gameCode)->config ?? [];

        // 配置路径
        $configPaths = array_keys(Arr::dot(ConfigPlatform::getConfigStruct($gameCode)));
        // 设置缺省值
        foreach ($configPaths as $path) {
            // data_fill($configPlatform, $path, data_get($configSystem, $path));
            data_fill($configPlatform, $path, data_get($configPaths, $path));
        }

        return $configPlatform;
    }

    /**
     * 更新配置【平台】
     *
     * @param string $gameCode
     * @param string $platCode
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function updatePlat($gameCode, $platCode, $request)
    {
        // 配置数据映射
        $data = DataMapper::make($request)->toArray();
        // 创建或修改配置
        $config = ConfigPlatform::updateOrCreateByPlatGame($platCode, $gameCode, $data);

        // 通知游戏端配置修改
        $config->syncGameService();

        return $this->getConfigPlat($gameCode, $platCode);
    }
}
